﻿using MySchool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WinForm6
{
    public partial class Form1 : Form
    {
        DBHelper dBHelper = new DBHelper();

        DataSet ds = new DataSet();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 初始化
            init();
           
        }

        private void init()
        {
            // 查询
            dBHelper.OpenConnection();
            string sql = "select u.Id,u.username,g.gname from sys_user u inner join Grade g on u.g_id = g.Id ";
            SqlDataAdapter adapter = new SqlDataAdapter(sql, dBHelper.Connection);
            adapter.Fill(ds, "sys_user");
            this.dataGridView1.DataSource = ds.Tables["sys_user"];
            dBHelper.CloseConnection();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //DataView 提供属性来筛选数据
            DataView view = new DataView(ds.Tables["sys_user"]);
            if (this.treeView1.SelectedNode.Level == 0)
            {
            }
            else {
                view.RowFilter = "gname = '" + this.treeView1.SelectedNode.Text + "'";
            }
            this.dataGridView1.DataSource = view;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("是否删除数据？","删除",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                // 执行删除的逻辑
                // 获取要删除数据的编号
                int id = Convert.ToInt32(this.dataGridView1.SelectedRows[0].Cells["Id"].Value);
                dBHelper.OpenConnection();
                string sql = "delete from sys_user where id = " + id;
                SqlCommand command = new SqlCommand(sql,dBHelper.Connection);
                int count = command.ExecuteNonQuery();
                if (count > 0) {
                    MessageBox.Show("删除成功！");
                    ds.Tables["sys_user"].Clear();
                    // 再加载数据
                    init();
                }
            }
            else {

            }


        }
    }
}
